<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 11-6/2014
 * Time: 11:28
 */
include 'config.inc.php';

//echo PHP_EOL . "=============DEBUG BEGIN===============".PHP_EOL;
//TODO::获取对方删除的产品，我们也将产品下架，
//注意：必须根据account来分组！不同的账号会有相同的产品ID
$sql = <<<SQL
SELECT id,product_ids,account FROM get_Product_Fromt_Action
WHERE dstatus=0 AND t_get=2 AND product_ids<>''
SQL;
$stmt = $pdo->prepare($sql);
$stmt->execute();
$rmPids = array();
while ($tmp = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $idList[]     = $tmp['id'];
    $rmPids[$tmp['account']][] = $tmp['product_ids'];
}
if (count($rmPids)) {
    foreach ($rmPids as $ac=>$pids) {
        $remote_pid = implode(',', array_unique($pids));
        //获取票付通的产品id
        $sql_pft_pid = "SELECT pid FROM get_Product_Fromt_Lib WHERE remoteid IN($remote_pid)";
        $stmt = $pdo->prepare($sql_pft_pid);
        $pft_pid_list = $stmt->fetchColumn(0);
        //将票付通平台产品下架
        if ($pft_pid_list) {
            $sql_pft = "UPDATE uu_products SET apply_limit=2,verify_time=now()"
                ." WHERE id IN(".implode(',', $pft_pid_list).")";
            $pdo->exec($sql_pft);
        }
    }
    //更新记录状态
    $sql_chg_state = "UPDATE get_Product_Fromt_Action SET dstatus=1 WHERE id IN(".implode(',', $idList).")";
    $pdo->exec($sql_chg_state);
}


//TODO::获取未执行的记录
$sql = <<<SQL
SELECT id,account,product_ids,t_get,dstatus FROM get_Product_Fromt_Action
WHERE dstatus=0 AND t_get=1 AND product_ids<>''
SQL;
$stmt = $pdo->prepare($sql);
$stmt->execute();
$accountWithRemoteId = array();
while($tmp = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $accountWithRemoteId[$tmp['account']][] = $tmp['product_ids'];
    $dataUnHandler[$tmp['account']][]       = $tmp;
}
//print_r($accountWithRemoteId);
//print_r($dataUnHandler);
//exit;
if (!$dataUnHandler) {
    ProductApi::writeLog(ProductApi::now() . '|没有未执行的记录', 'autorun');
    exit;
}
foreach($accountWithRemoteId as $acc=>$pid) {
    $pidStr = implode(',', $pid);//先将所有id转成字符串
    $pidArr = explode(',', $pidStr);
    $accountWithRemoteId[$acc] = array_unique($pidArr, SORT_NUMERIC);
}
//print_r($accountWithRemoteId);

$sql = "SELECT id,t_url,t_notice_url,account FROM get_Product_Fromt_Info";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$infoList = array();
while($info = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $infoList[$info['account']] = $info;
}
$date_time = $_SERVER['REQUEST_TIME'];
//print_r($infoList);
//echo PHP_EOL . "=============DEBUG END===============".PHP_EOL;
//exit;
foreach ($accountWithRemoteId as $account=>$remoteIdList) {
    //TODO::handler verifycode
    $sql_member = "SELECT password FROM pft_member WHERE account=$account LIMIT 1";
    $stmt = $pdo->prepare($sql_member);
    $stmt->execute();
    $password = $stmt->fetchColumn(0);
    $verifyCode = md5('pft'.substr($password, 0, 16) . '12301');
    $handlerFailPid = array();
    //TODO::循环获取产品数据
    foreach ($remoteIdList as $remoteId) {
        $xml = <<< XML
<?xml version="1.0" encoding="UTF-8"?>
<request xsi:schemaLocation="http://open.12301.cc/2014/ResponseSchema ResponseDataSchema-2.3.0.xsd" xmlns="http://open.12301.cc/2014/ResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <header>
        <application>PFT.API.Agent</application>
        <processor>PFTDataExchange</processor>
        <version>v2.3.0</version>
        <bodyType>PFTProductCatchRequestBody</bodyType>
        <account>{$account}</account>
        <verifycode>{$verifyCode}</verifycode>
    </header>
    <body xsi:type="PFTProductCatchRequestBody">
        <resourceId>{$remoteId}</resourceId>
    </body>
</request>
XML;
        echo $xml;
        $request_data = json_encode(
            array(
                'method' => 'ProductCatch',
                'data'   => base64_encode($xml),
            )
        );
        $responseXml = raw_post($infoList[$account]['t_url'], $request_data);
//        $responseXml = file_get_contents($infoList[$account]['t_url']);
//        echo($responseXml);
//        exit;
        //处理产品数据
        $handlerJson  = raw_post('http://localhost/new/d/api/handler.php', $responseXml);
//        echo $handlerJson;
        $handlerArr = json_decode($handlerJson);
//        print_r($handlerArr);
//        exit;
        //执行失败
        if ($handlerArr->code != 200) {
            $req_method = 'ProductError';

            //处理失败要下架
            $sqlGetPid = <<<SQL
SELECT pid FROM get_Product_Fromt_Lib
WHERE account='{$data['account']}' AND remoteid={$handlerArr->pid}
LIMIT 1
SQL;
            $stmt = $pdo->prepare($sqlGetPid);
            $stmt->execute();
            $pid = $stmt->fetchColumn(0);
            if ($pid) {
                $sql = "UPDATE uu_products SET apply_limit=2,verify_time=now() WHERE id=$pid LIMIT 1";
                $this->db->exec($sql);
            }
            //处理失败要下架结束
            $handlerFailPid[] = $handlerArr->pid;
            //TODO::通知处理结果
            $xmlError = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:schemaLocation="http://open.12301.cc/2014/ResponseSchema ResponseDataSchema-2.3.0.xsd" xmlns="http://open.12301.cc/2014/ResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <header>
        <application>PFT.API.Agent</application>
        <processor>PFTDataExchange</processor>
        <version>v2.3.0</version>
        <bodyType>PFTProductErrorRequestBody</bodyType>
        <account>{$account}</account>
        <verifycode>{$verifyCode}</verifycode>
    </header>
    <body xsi:type="PFTProductErrorRequestBody">
        <code>{$handlerArr->code}</code>
        <product_id>{$handlerArr->pid}</product_id>
        <date_time>{$date_time}</date_time>
    </body>
</request>
XML;
            $request_data = json_encode(
                array(
                    'method' => $req_method,
                    'data'   => base64_encode($xmlError),
                )
            );
            raw_post($infoList[$data['account']]['t_notice_url'], $request_data);
        }
        else {
//            $req_method = 'ProductSuccess';
            $handlerSuccessPid[] = $handlerArr->remote_id;
            if ($handlerArr->mode==0) {
                //TODO::如果为新增产品，更新外部抓取产品库
                $sql = <<<SQL
UPDATE get_Product_Fromt_Lib SET pid={$handlerArr->pid}
WHERE remoteid={$handlerArr->remote_id} AND account='{$account}' LIMIT 1
SQL;
                try {
                    $pdo->exec($sql);
                } catch(PDOException $e) {

                }
            }
        }


    }

    //TODO::处理结果,更新状态
    if (count($handlerSuccessPid)) {
        //TODO::执行成功，更新状态
        foreach ($handlerSuccessPid as $succeePid) {
            $sqlSetStatus = <<<SQL
UPDATE get_Product_Fromt_Action SET dstatus=1,dtime=now()
WHERE account=$account AND FIND_IN_SET($succeePid, `product_ids`)>0
SQL;
            $pdo->exec($sqlSetStatus);
        }
    }
    if (count($handlerFailPid)) {
        //TODO::执行失败，更新状态
        foreach ($handlerFailPid as $failPid) {
            $sqlSetStatus = <<<SQL
UPDATE get_Product_Fromt_Action SET dstatus=2,dtime=now()
WHERE account=$account AND FIND_IN_SET($failPid, `product_ids`)>0
SQL;
            $pdo->exec($sqlSetStatus);
        }
    }
}


// 报文加密流程：base64_encode->数组array('method'=>'ProductCatch','data'=>base64字符串)->json_encode
